from utils.common_import import *
from .model import IntervalQuerySchema
from .dashboard import get_time_day_edge_second, sample_prometheus_series, \
    HOUR_UNIT_TIME_SECOND, DAY_UNIT_TIME_SECOND
from config.prometheus_metric import PrometheusMetric

class ResourceCpuView(Resource):
    # @jwt_required()
    @request_arg_check(IntervalQuerySchema(), location="args")
    @exception_response()
    def get(self):
        interval = current_schema_instance["query_interval"]
        time_range = get_time_day_edge_second(interval)
        now_time = time_range["now_time"]
        begin_day_time = time_range["start_day"]

        # cpu_exp = '100-(avg by(job)(rate(node_cpu_seconds_total{mode="idle"}[1d]))*100)'
        result = cluster_client.prometheus_client.query_range(
            PrometheusMetric.CLUSTER_CPU,
            begin_day_time,
            now_time,
            step=DAY_UNIT_TIME_SECOND)

        #标准化输出
        utilization = self._format_result(result)

        return  make_success_response(utilization)

    def _format_result(self, result):
        if result["data"]["result"] and "values" in  result["data"]["result"][0]:
            utilization = result["data"]["result"][0]["values"]
        else:
            utilization = []
        #将秒转为毫秒
        for utilization_sample in utilization:
            utilization_sample[0] *= 1000
            utilization_sample[1] = float("{:.2f}".format(float(utilization_sample[1])))

        return utilization


class ResourceMemoryView(Resource):
    # @jwt_required()
    @request_arg_check(IntervalQuerySchema(), location="args")
    @exception_response()
    def get(self):
        interval = current_schema_instance["query_interval"]
        time_range = get_time_day_edge_second(interval)
        now_time = time_range["now_time"]
        begin_day_time = time_range["start_day"]

        # memory_total_used_exp = "100*(sum(avg_over_time(node_memory_MemTotal_bytes[1d])) " \
        # "- sum(avg_over_time(node_memory_MemFree_bytes[1d])) " \
        # "- sum(avg_over_time(node_memory_Buffers_bytes[1d])) " \
        # "- sum(avg_over_time(node_memory_Cached_bytes[1d]))) " \
        # "/ sum(avg_over_time(node_memory_MemTotal_bytes[1d]))"


        result = cluster_client.prometheus_client.query_range(
                                        PrometheusMetric.CLUSTER_MEMORY,
                                        begin_day_time,
                                        now_time,
                                        step=DAY_UNIT_TIME_SECOND)

        #标准化输出
        utilization = self._format_result(result)

        return  make_success_response(utilization)

    def _format_result(self, result):
        if result["data"]["result"] and "values" in  result["data"]["result"][0]:
            utilization = result["data"]["result"][0]["values"]
        else:
            utilization = []
        #将秒转为毫秒
        for utilization_sample in utilization:
            utilization_sample[0] *= 1000
            utilization_sample[1] = float("{:.2f}".format(float(utilization_sample[1])))

        return utilization


class ResourceGpuUtilView(Resource):
    # @jwt_required()
    @request_arg_check(IntervalQuerySchema(), location="args")
    @exception_response()
    def get(self):
        interval = current_schema_instance["query_interval"]
        time_range = get_time_day_edge_second(interval)
        now_time = time_range["now_time"]
        begin_day_time = time_range["start_day"]

        # gpu_util_exp = "avg(avg_over_time(nvidiasmi_utilization_gpu[1d]))"

        result = cluster_client.prometheus_client.query_range(
                                        PrometheusMetric.CLUSTER_DEV_UTIL,
                                        begin_day_time,
                                        now_time,
                                        step=DAY_UNIT_TIME_SECOND)

        utilization_list = sample_prometheus_series(result, begin_day_time, interval)

        return  make_success_response(utilization_list)

class ResourceGpuAllocateView(Resource):
    # @jwt_required()
    @request_arg_check(IntervalQuerySchema(), location="args")
    @exception_response()
    def get(self):
        interval = current_schema_instance["query_interval"]
        time_range = get_time_day_edge_second(interval)
        now_time = time_range["now_time"]
        begin_day_time = time_range["start_day"]

        logger.info("begin_day_time is {}".format(begin_day_time))
        # gpu_allocate_ratio_exp = "(1 - (sum(yarn_node_gpu_available)/sum(yarn_node_gpu_total)))"

        result = cluster_client.prometheus_client.query_range(
                                        PrometheusMetric.CLUSTER_DEV_ALLOCATE,
                                        begin_day_time,
                                        now_time,
                                        step=HOUR_UNIT_TIME_SECOND)

        utilization_list = sample_prometheus_series(result, begin_day_time, interval)

        return  make_success_response(utilization_list)


